package com.bidepan.big_event.interceptors;

import com.bidepan.big_event.pojo.Result;
import com.bidepan.big_event.utils.JwtUtil;
import com.bidepan.big_event.utils.ThreadLocalUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;

/*
    拦截器：设置在请求之前的准备工作(如令牌校验，荷载保存)或请求完成之后的收尾工作(如ThreadLocal中的数据回收防止内存泄漏)
 */

@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //令牌验证
        String token = request.getHeader("Authorization");
        //验证token
        try{
            //从redis中获取相同的token
            String redisToken = redisTemplate.opsForValue().get(token);
            if(redisToken == null){
                //token已失效
                throw new RuntimeException();
            }
            Map<String,Object> claims = JwtUtil.parseToken(token);
            //把业务数据存储到ThreadLocal中，既可以减少后续方法的参数，又可以实现线程隔离
            ThreadLocalUtil.set(claims);
            return true;   //令牌解析未捕获异常，放行
        }catch (Exception e){
            //http响应状态码为401
            response.setStatus(401);
            return false;  //捕获异常，不放行
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //清空ThreadLocal中的数据，以防内存泄漏
        ThreadLocalUtil.remove();
    }
}
